import React, { useState, useEffect } from 'react';
import { Form, Input, Modal, Select, TreeSelect, DatePicker } from 'antd';
import { queryDeviceList } from '@/services/device';
import moment from 'moment';

const { TextArea } = Input;

const { Option } = Select;

const FormItem = Form.Item;

export interface UpdateFormProps {
  onCancel: () => void;
  onSubmit: (values: API.DefectRecordItem) => void;
  updateModalVisible: boolean;
  values: API.DepartmentItem;
  treeData?: API.TreeNodeItem[];
  userData?: API.UserItem[];
}

const formLayout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 15 },
};

const UpdateForm: React.FC<UpdateFormProps> = (props) => {
  const [formVals] = useState<API.DefectRecordItem>(props.values);

  const [form] = Form.useForm();

  const [deviceData, setDeviceData] = useState<API.DeviceItem[]>([]);

  const { updateModalVisible, onSubmit: handleUpdate,  onCancel, treeData, userData} = props;

  const okHandle = async () => {
    const fieldsValue = await form.validateFields();
    fieldsValue.defectId = formVals.defectId;
    if (fieldsValue.findTime) {
      fieldsValue.findTime = fieldsValue.findTime.format('YYYY-MM-DD hh:mm:ss');
    }
    if (fieldsValue.defectEliminationTime) {
      fieldsValue.defectEliminationTime = fieldsValue.defectEliminationTime.format('YYYY-MM-DD hh:mm:ss');
    }
    form.resetFields();
    handleUpdate(fieldsValue);
  };

  const onChange = async (value: string, label: any[]) => {
    const dList = await queryDeviceList({ areaId: value });
    setDeviceData(dList);
  };

  const setStateData = async () => {
    const dList = await queryDeviceList();
    setDeviceData(dList);
  };

  useEffect(() => {
    setStateData();
  }, []);

  return (
    <Modal
      width={640}
      destroyOnClose
      title="编辑缺陷"
      visible={updateModalVisible}
      onOk={okHandle}
      onCancel={() => onCancel()}
    >
      <Form
        {...formLayout}
        form={form}
        initialValues={{
          deviceId: formVals.deviceId,
          areaId: formVals.areaId+'',
          location: formVals.location,
          defect: formVals.defect,
          defectSource: formVals.defectSource,
          jobRecordId: formVals.jobRecordId,
          findPeople: formVals.findPeople,
          findTime: formVals.findTime?moment(formVals.findTime, 'YYYY-MM-DD hh:mm:ss'):'',
          defectEliminationPerson: formVals.defectEliminationPerson,
          defectEliminationTime: formVals.defectEliminationTime?moment(formVals.defectEliminationTime, 'YYYY-MM-DD hh:mm:ss'):'',
          rectificationPlan: formVals.rectificationPlan,
        }}
      >
        <FormItem
          label="设备所在区域"
          name="areaId"
          rules={[{ required: true, message: '请选择所在区域' }]}
        >
          <TreeSelect
            style={{ width: '100%' }}
            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
            treeData={treeData}
            onChange={onChange}
            placeholder="请选择所在区域"
            key="key"
            treeDefaultExpandAll
          />
        </FormItem>
        <FormItem
          label="设备名称"
          name="deviceId"
          rules={[{ required: true, message: '请输入设备名称' }]}
        >
          <Select
            showSearch
            placeholder={'请选择设备'}
            filterOption={(input, option) =>
              option?.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
            }
          >
            {deviceData?.map((item) => (
              <Option key={item.deviceId} value={item.deviceId ?? ''}>
                {item.deviceName}
              </Option>
            ))}
          </Select>
        </FormItem>
        <FormItem
          label="缺陷地点"
          name="location"
          rules={[{ required: true, message: '请输入缺陷地点' }]}
        >
          <Input placeholder="请输入" autoComplete='off' />
        </FormItem>
        <FormItem
          label="缺陷内容"
          name="defect"
          rules={[{ required: true, message: '请输入缺陷内容' }]}
        >
          <TextArea placeholder="请输入" showCount maxLength={100} />
        </FormItem>
        <FormItem
          label="发现人"
          name="findPeople"
        >
          <Select
            showSearch
            placeholder="请选择发现人"
            filterOption={(input, option) =>
              option?.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
            }
          >
            {userData?.map((item) => (
              <Option key={item.userId} value={item.userId ?? ''}>
                {item.realName}
              </Option>
            ))}
          </Select>
        </FormItem>
        <FormItem
          label="发现时间"
          name="findTime"
        >
          <DatePicker placeholder='请选择' style={{ width: '100%' }} showTime={true} />
        </FormItem>
        <FormItem
          label="消缺人"
          name="defectEliminationPerson"
        >
          <Select
            showSearch
            placeholder="请选择消缺人"
            filterOption={(input, option) =>
              option?.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
            }
          >
            {userData?.map((item) => (
              <Option key={item.userId} value={item.userId ?? ''}>
                {item.realName}
              </Option>
            ))}
          </Select>
        </FormItem>
        <FormItem
          label="消缺时间"
          name="defectEliminationTime"
        >
          <DatePicker placeholder='请选择' style={{ width: '100%' }} showTime={true} />
        </FormItem>
        <FormItem
          label="整改方案"
          name="rectificationPlan"
        >
          <TextArea placeholder="请输入" showCount maxLength={100} />
        </FormItem>
      </Form>
    </Modal>
  );
};

export default UpdateForm;
